package grobit.torrent

import org.apache.commons.codec.binary.Base64

import java.security.MessageDigest

class Sha1Data {
    private byte[] data = new byte[20]

    Sha1Data(byte[] data) {
        assert data?.length == 20
        System.arraycopy(data, 0, this.data, 0, this.data.length)
    }

    byte[] getBytes() {
        byte[] rv = new byte[data.length]
        System.arraycopy(data, 0, rv, 0, data.length)
        return rv
    }

    public equals(Sha1Data other) {
        return data == other.data
    }

    String asString() {
        return new String(data, 'ISO8859-1')
    }

    String toString() {
        return new String(Base64.encodeBase64(data), 'UTF-8')
    }

    String asHexString() {
        StringBuilder builder = new StringBuilder()
        data.each { builder.append(String.format("%02x", it)) }
        return builder.toString()
    }

    static Sha1Data calculateSha1(String s) {
        MessageDigest md = MessageDigest.getInstance('SHA-1')
        return new Sha1Data(md.digest(s.getBytes('ISO-8859-1')))
    }
}
